package com.fesine.realm;

import com.fesine.entity.User;
import com.fesine.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * Created by Fesine on 2016/6/13.
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    Logger logger = Logger.getLogger(MyRealm.class);

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();//获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //通过用户名获取角色
        authorizationInfo.setRoles(userService.getRoles(userName));
        //通过用户名获取权限
        authorizationInfo.setStringPermissions(userService.getPermissions(userName));
        return authorizationInfo;
    }

    /**
     * 验证当前登录的用户
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        String userName = (String) token.getPrincipal();//获取用户名
        User user = userService.getByUserName(userName);//根据用户名查询用户信息
        if (user != null) {
            //封装验证信息，用户名和密码，私钥，与提交的用户数据进行比对
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
                    user.getUserName(), user.getPassword(), "fesine");
            return authcInfo;
        } else {
            logger.info("用户名不存在！");
            return null;
        }
    }
}
